package com.tobearc.persist.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 
 * @author yangqifan
 */
public class HttpClient implements IClient {
	
	static String urlstring = "http://localhost:1234";

	public boolean connect() {
		return false;
	}
	
	public static boolean post(String urladdress, String param)
			throws Exception {
		HttpURLConnection uc = null;
		if(urladdress == null)urladdress = urlstring;
		try {
			URL url = new URL(urladdress);

			uc = (HttpURLConnection) url.openConnection();
			uc.setDoInput(true);
			uc.setDoOutput(true);
			uc.setInstanceFollowRedirects(true); // 不允许重定向
			uc.setRequestMethod("POST");
			uc.setConnectTimeout(5000); // 五秒连接超时
			uc.setReadTimeout(5000); // 5秒返回超时
			uc.getOutputStream().write(param.getBytes());
			uc.connect();
			int t = uc.getResponseCode();
			System.out.println("发送到" + urladdress + "\r\n resultcode=" + t);
			// if(logger.isDebugEnabled()){
			try {
				String responseMessage = uc.getResponseMessage();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(uc.getInputStream()));
				String lines = "";
				while (reader.ready()) {
					lines += reader.readLine();
				}
				reader.close();
				System.out.println("返回值" + t + " " + responseMessage + " \n" + lines);
			} catch (Exception e) {
				System.err.println(e);
			}
			// }
			return true;

		} catch (Exception e) {
		} finally {
			if (uc != null && uc.getInputStream() != null) {
				// uc.disconnect();//释放资源，并有可能影响到持久连接
				uc.getInputStream().close();// 只释放实例资源，不会影响持久连接
			}
		}
		return false;
	}

	public static void main(String[] args) {
		try {
			StringBuilder builder = new StringBuilder();
			for(int i = 0; i < 2000; i++){
				builder.append("test");
			}
			post(null, builder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
